package com.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.common.Param;
import com.crm.domain.dto.ActiveDTO;
import com.crm.domain.entity.Active;
import com.crm.domain.vo.RowsVO;
import com.crm.domain.vo.DataVO;
import com.crm.mapper.ActiveMapper;
import com.crm.mapper.DictTypeMapper;
import com.crm.service.ActiveService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 15890
 */
@Service
@RequiredArgsConstructor
public class ActiveServiceImpl extends ServiceImpl<ActiveMapper, Active> implements ActiveService {

    private static final String CHAR_POOL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int LENGTH = 8;
    private static final SecureRandom random = new SecureRandom();
    private final ActiveMapper activeMapper;
    private final DictTypeMapper dictTypeMapper;

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @param code
     * @param channel
     * @param beginCreateTime
     * @param endCreateTime
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public RowsVO listByPage(Integer pageNum, Integer pageSize, String code, Integer channel, String beginCreateTime, String endCreateTime, String beginTime, String endTime) {
        Page<Active> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Active> queryWrapper = new QueryWrapper<>();

        // 构建查询条件
        if (code != null && !code.isEmpty()) {
            queryWrapper.like("code", code);
        }
        if (channel != null) {
            queryWrapper.eq("channel", channel);
        }
        // 处理创建时间范围查询
        if (beginCreateTime != null && !beginCreateTime.isEmpty() && endCreateTime != null && !endCreateTime.isEmpty()) {
            queryWrapper.between("create_time", beginCreateTime, endCreateTime);
        }
        // 处理活动时间范围查询
        if (beginTime != null && !beginTime.isEmpty() && endTime != null && !endTime.isEmpty()) {
            queryWrapper.between("begin_time", beginTime, endTime);
        }
        Page<Active> result = activeMapper.selectPage(page, queryWrapper);
        List<Active> records = result.getRecords();
        Param param = new Param();
        records.forEach(i -> {
            Character status = i.getStatus();
            if (status == '1') {
                param.setReject(param.getReject() + 1);
            } else if (status == '2') {
                param.setPass(param.getPass() + 1);
            } else if (status == '3') {
                param.setToAudit(param.getToAudit() + 1);
            } else if (status == '4') {
                param.setFinish(param.getFinish() + 1);
            }
// 可以添加else来处理未知情况
        });
        param.setTotal(records.size());
        RowsVO rowsVO = new RowsVO();
        rowsVO.setParams(param);
        rowsVO.setRows(records);
        rowsVO.setTotal(result.getTotal());
        rowsVO.setCode(200);
        rowsVO.setMsg("操作成功");
        return rowsVO;
    }

    /**
     * 增
     * @param dto
     */
    @Override
    public void add(ActiveDTO dto) {
        Active bean = BeanUtil.toBean(dto, Active.class);
        bean.setCreateTime(LocalDateTime.now());
        bean.setUpdateTime(LocalDateTime.now());
        bean.setCreateBy("admin");
        bean.setUpdateBy("admin");
        System.out.println(bean);
        while (true){

            String s = creatActiveCode();
            QueryWrapper<Active> wrapper = new QueryWrapper<>();
            wrapper.eq("code", s);
            Long l = activeMapper.selectCount(wrapper);
            if(l==0){
                bean.setCode(s);
                activeMapper.insert(bean);
                break;
            }
        }


    }



    public static String creatActiveCode() {
        StringBuilder captcha = new StringBuilder(LENGTH);
        for (int i = 0; i < LENGTH; i++) {
            // 生成一个随机数，范围从0到CHAR_POOL的长度（包括）
            int randomIndex = random.nextInt(CHAR_POOL.length());
            // 将随机索引对应的字符添加到验证码字符串中
            captcha.append(CHAR_POOL.charAt(randomIndex));
        }
        System.out.println(captcha.toString());
        return captcha.toString();
    }

}
